package org.domeos.configuration;

import javax.sql.DataSource;

import org.domeos.global.GlobalConstant;
import org.domeos.util.DatabaseType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.taobao.tddl.group.jdbc.TGroupDataSource;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"org.domeos.framework.api.mapper.domeos"}, sqlSessionFactoryRef = "domeosSqlSessionFactory")
public class DomeOSConfiguration {
	
	@Value("${gdocker.mysql.dbGroupKey}")
	private String dbGroupKey;
	
	@Value("${gdocker.mysql.appName}")
	private String appName;

    @Bean(initMethod = "init", name = "domeosDataSource")
    @Primary
    public DataSource domeosDataSource() throws Exception {
    	TGroupDataSource dataSource = new TGroupDataSource(dbGroupKey, appName);
        return dataSource;
    }

    @Bean(name = "domeosTransactionManager")
    @Primary
    public DataSourceTransactionManager domeosTransactionManager() throws Exception {
        return new DataSourceTransactionManager(domeosDataSource());
    }

    @Bean(name = "domeosSqlSessionFactory")
    @Primary
    public SqlSessionFactoryBean sqlSessionFactory(@Qualifier("domeosDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        GlobalConstant.DATABASETYPE = DatabaseType.MYSQL;
        return sessionFactory;
    }

}
